<template>
  <el-dialog 
    v-model="dialogVisible" 
    :title="dialogTitle" 
    width="500px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form 
      ref="formRef" 
      :model="formData" 
      :rules="rules" 
      label-width="100px"
      class="category-form"
    >
      <!-- 分类名称 -->
      <el-form-item label="分类名称" required prop="categoryName">
        <el-input
          v-model="formData.categoryName"
          placeholder="请输入分类名称"
          clearable
        />
      </el-form-item>

      <!-- 分类图片 -->
      <el-form-item label="分类图片" required prop="categoryImage">
        <div class="image-upload-container">
          <el-upload
            class="image-uploader"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :on-error="handleImageError"
            action="#"
            :auto-upload="false"
            :on-change="handleImageChange"
          >
            <div class="upload-area" v-if="!formData.categoryImage">
              <el-icon class="upload-icon">
                <Plus />
              </el-icon>
              <div class="upload-text">点击上传图片</div>
            </div>
            <img 
              v-else 
              :src="formData.categoryImage" 
              class="uploaded-image" 
              alt="分类图片"
            />
          </el-upload>
        </div>
      </el-form-item>

      <!-- 排序 -->
      <el-form-item label="排序" prop="sortOrder">
        <el-input-number
          v-model="formData.sortOrder"
          :min="1"
          :max="999"
          controls-position="right"
          class="sort-input"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ submitButtonText }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const props = defineProps(['cateDialogVisible', 'editCateData', 'closeCateDialog'])
const emit = defineEmits(['submit-cate'])

// 响应式数据
const dialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref(null)

// 计算属性
const dialogTitle = computed(() => {
  return props.editCateData ? '修改分类' : '添加分类'
})

const submitButtonText = computed(() => {
  return props.editCateData ? '立即修改' : '立即添加'
})

// 表单数据
const formData = reactive({
  categoryName: '',
  categoryImage: '',
  sortOrder: 1
})

// 表单验证规则
const rules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 20, message: '分类名称长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  categoryImage: [
    { required: true, message: '请上传分类图片', trigger: 'change' }
  ]
}

// 监听父组件传递的显示状态
watch(() => props.cateDialogVisible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    // 如果有编辑数据，填充表单；否则重置表单
    if (props.editCateData) {
      fillFormWithEditData()
    } else {
      resetForm()
    }
  }
}, { immediate: true })

// 重置表单
const resetForm = () => {
  formData.categoryName = ''
  formData.categoryImage = ''
  formData.sortOrder = 1
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 填充编辑数据到表单
const fillFormWithEditData = () => {
  if (props.editCateData) {
    formData.categoryName = props.editCateData.name || ''
    formData.categoryImage = props.editCateData.address || ''
    formData.sortOrder = parseInt(props.editCateData.order) || 1
  }
}

// 图片上传处理
const handleImageChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.categoryImage = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const handleImageSuccess = (response, file) => {
  formData.categoryImage = URL.createObjectURL(file.raw)
}

const handleImageError = () => {
  ElMessage.error('图片上传失败，请重试')
}

const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 准备提交数据
    const submitData = {
      categoryName: formData.categoryName,
      categoryImage: formData.categoryImage,
      sortOrder: formData.sortOrder
    }
    
    // 如果是编辑模式，添加ID
    if (props.editCateData) {
      submitData.id = props.editCateData.id
    }
    
    // 模拟提交数据
    setTimeout(() => {
      emit('submit-cate', submitData)
      ElMessage.success(props.editCateData ? '分类修改成功!' : '分类添加成功!')
      submitLoading.value = false
      handleClose()
    }, 1000)
    
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

// 取消操作
const handleCancel = () => {
  handleClose()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  props.closeCateDialog()
  resetForm()
}
</script>

<style lang="scss" scoped>
.category-form {
  .image-upload-container {
    .image-uploader {
      :deep(.el-upload) {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: all 0.3s;
        
        &:hover {
          border-color: #409eff;
        }
      }
    }

    .upload-area {
      width: 120px;
      height: 120px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #8c939d;
      font-size: 14px;
      
      .upload-icon {
        font-size: 28px;
        margin-bottom: 8px;
      }
      
      .upload-text {
        font-size: 12px;
      }
    }

    .uploaded-image {
      width: 120px;
      height: 120px;
      object-fit: cover;
      border-radius: 6px;
    }
  }

  .sort-input {
    width: 120px;
  }
}

.dialog-footer {
  text-align: right;
  
  .el-button {
    margin-left: 10px;
  }
}

// 必填项红色星号样式
:deep(.el-form-item.is-required .el-form-item__label::before) {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
</style>
